package com.example.administrator.ygddriver.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
import com.example.administrator.ygddriver.tool.UrlValuse;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

/**
 * 微信登陆返回
 */
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    private IWXAPI api;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        api = WXAPIFactory.createWXAPI(this, UrlValuse.WXAPP_ID, true);
        api.handleIntent(getIntent(), this);

    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp baseResp) {
        if (baseResp.getType() == ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX) {
            Toast.makeText(WXEntryActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
            finish();
        } else if (baseResp.errCode == 0) {
            String s = ((SendAuth.Resp) baseResp).code;
            OkGo.<String>get("https://api.weixin.qq.com/sns/oauth2/access_token?appid="+UrlValuse.WXAPP_ID+"&secret=d28315fc508fad9765fd5be4be7ef939&code=" + s + "&grant_type=authorization_code").execute(new StringCallback() {
                @Override
                public void onSuccess(Response<String> response) {
                    Gson gson = new Gson();
                    WxRequestBean wxRequestBean = gson.fromJson(response.body(), WxRequestBean.class);
                    wxRequestBean.getAccess_token();
                    wxRequestBean.getOpenid();
                    Intent intent = new Intent();
                    intent.putExtra("access_token", wxRequestBean.getAccess_token());
                    intent.putExtra("openid", wxRequestBean.getOpenid());
                    intent.setAction(UrlValuse.WX_BD_ZT);
                    sendBroadcast(intent);
                }
            });
        }
        finish();
    }


}
